package com.gc.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.lang.Console;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gc.business.domain.CommunityManage;
import com.gc.business.domain.CompanyManage;
import com.gc.business.domain.ElevatorTiring;
import com.gc.business.domain.GovManage;
import com.gc.business.mapper.CommunityManageMapper;
import com.gc.business.mapper.CompanyManageMapper;
import com.gc.business.mapper.GovManageMapper;
import com.gc.business.service.ICommunityManageService;
import com.gc.business.service.ICompanyManageService;
import com.gc.common.constant.BusinessConstants;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gc.common.annotation.DataScope;
import com.gc.common.constant.UserConstants;
import com.gc.common.exception.BusinessException;
import com.gc.common.support.Convert;
import com.gc.common.utils.Md5Utils;
import com.gc.common.utils.StringUtils;
import com.gc.system.domain.SysPost;
import com.gc.system.domain.SysRole;
import com.gc.system.domain.SysUser;
import com.gc.system.domain.SysUserPost;
import com.gc.system.domain.SysUserRole;
import com.gc.system.mapper.SysPostMapper;
import com.gc.system.mapper.SysRoleMapper;
import com.gc.system.mapper.SysUserMapper;
import com.gc.system.mapper.SysUserPostMapper;
import com.gc.system.mapper.SysUserRoleMapper;
import com.gc.system.service.ISysConfigService;
import com.gc.system.service.ISysUserService;

/**
 * 用户 业务层处理
 *
 * @author gc
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private GovManageMapper govManageMapper;

    @Autowired
    private CompanyManageMapper companyManageMapper;

    @Autowired
    private ICompanyManageService companyManageService;

    @Autowired
    private CommunityManageMapper communityManageMapper;

    @Autowired
    private ICommunityManageService communityManageService;

    /**
     * 根据条件分页查询用户对象
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(tableAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }

    /**
     * 查询不同小区所归属的用户列表
     * @param attrId
     * @return
     */
    @Override
    public List<SysUser> selectUserListByCommunityAttrId(Long attrId){
       if(attrId != null && attrId == 0){
           //平台查询
           List<CommunityManage> communityList = communityManageService.list(new CommunityManage());
           String communityIds = "";
           for (CommunityManage communityManage : communityList) {
               communityIds = communityIds + communityManage.getCommunityId() + ",";
           }
           return userMapper.selectUserListInAttrIds(Convert.toLongArray(communityIds));
       }else{
           List<SysUser> userList = null;
           switch (this.checkUserRoleByAttrId(attrId).getRoleKey()){
               case BusinessConstants.GOV :
                    //政府机构
                   String communityIdsByGov = "";
                   List<CommunityManage> communityListByGov = communityManageService.selectCommunityByAttrId(attrId);
                   for (CommunityManage communityManage : communityListByGov) {
                       communityIdsByGov = communityIdsByGov + communityManage.getCommunityId() + ",";
                   }
                   userList = userMapper.selectUserListInAttrIds(Convert.toLongArray(communityIdsByGov == "" ? "0" : communityIdsByGov));
                   break;
               case BusinessConstants.COMPANY :
                    //公司
                   String communityIdsByCompany = "";
                   List<CommunityManage> communityListByCompany = communityManageService.selectCommunityByAttrId(attrId);
                   for (CommunityManage communityManage : communityListByCompany) {
                       communityIdsByCompany = communityIdsByCompany + communityManage.getCommunityId() + ",";
                   }
                   userList = userMapper.selectUserListInAttrIds(Convert.toLongArray(communityIdsByCompany == "" ? "0" : communityIdsByCompany));
                   break;
               case BusinessConstants.COMMUNITY :
                   //小区
                   userList = userMapper.selectUserList(new SysUser(){{setAttrId(attrId);}});
                   break;
           }
           return userList;
       }
    }

    @Override
    public List<SysUser> selectUserListByAttrId(Long attrId){
        return userMapper.selectUserListByAttrId(attrId);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByLoginName(String userName) {
        return userMapper.selectUserByLoginName(userName);
    }
    @Override
    public List<SysUser> selectUserByAttrId(Long attrId) {
        return userMapper.selectUserByAttrId(attrId);
    }

    /**
     * 通过手机号码查询用户
     *
     * @param phoneNumber 手机号码
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByPhoneNumber(String phoneNumber) {
        return userMapper.selectUserByPhoneNumber(phoneNumber);
    }

    /**
     * 通过邮箱查询用户
     *
     * @param email 邮箱
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByEmail(String email) {
        return userMapper.selectUserByEmail(email);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteUserByIds(String ids) throws BusinessException {
        Long[] userIds = Convert.toLongArray(ids);
        for (Long userId : userIds) {
            if (SysUser.isAdmin(userId)) {
                throw new BusinessException("不允许删除超级管理员用户");
            }
        }
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户个人详细信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserInfo(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetUserPwd(SysUser user) {
        return updateUserInfo(user);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0) {
                userPostMapper.batchUserPost(list);
            }
        }
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param loginName 用户名
     * @return
     */
    @Override
    public String checkLoginNameUnique(String loginName) {
        int count = userMapper.checkLoginNameUnique(loginName);
        if (count > 0) {
            return UserConstants.USER_NAME_NOT_UNIQUE;
        }
        return UserConstants.USER_NAME_UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.USER_PHONE_NOT_UNIQUE;
        }
        return UserConstants.USER_PHONE_UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.USER_EMAIL_NOT_UNIQUE;
        }
        return UserConstants.USER_EMAIL_UNIQUE;
    }

    /**
     * 查询用户所属角色组
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(Long userId) {
        List<SysRole> list = roleMapper.selectRolesByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    @Override
    public String selectUserRole(Long userId) {
        List<SysRole> list = roleMapper.selectRolesByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list) {
            idsStr.append(role.getRoleKey()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(Long userId) {
        List<SysPost> list = postMapper.selectPostsByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (SysPost post : list) {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new BusinessException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByLoginName(user.getLoginName());
                if (StringUtils.isNull(u)) {
                    user.setPassword(Md5Utils.hash(user.getLoginName() + password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 导入成功");
                } else if (isUpdateSupport) {
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getLoginName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getLoginName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 用户状态修改
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int changeStatus(SysUser user) {
        if (SysUser.isAdmin(user.getUserId())) {
            throw new BusinessException("不允许修改超级管理员用户");
        }
        return userMapper.updateUser(user);
    }


    /**
     * 根据归属ID验证身份，返回角色对象
     * @param attrId
     * @return
     */
    @Override
    public SysRole checkUserRoleByAttrId(Long attrId){

        //校验是否为政府机构
        GovManage govManage = govManageMapper.selectGovManageByGovId(attrId);
        if(StringUtils.isNotNull(govManage)){
            return roleMapper.checkRoleKeyUnique(BusinessConstants.GOV);
        }
        //校验是否为公司
        CompanyManage companyManage = companyManageMapper.selectCompanyManageByCompanyId(attrId);
        if(StringUtils.isNotNull(companyManage)){
            return roleMapper.checkRoleKeyUnique(BusinessConstants.COMPANY);
        }
        //校验是否为小区
        CommunityManage communityManage = communityManageMapper.selectCommunityManageByCommunityId(attrId);
        if(StringUtils.isNotNull(communityManage)){
            return roleMapper.checkRoleKeyUnique(BusinessConstants.COMMUNITY);
        }
        //全部不符合，返回null
        return null;
    }

    /**
     * 是否为公司人员
     * @param attrId
     * @return
     */
    @Override
    public Boolean ifCompanyRole(Long attrId){
        SysRole role = this.checkUserRoleByAttrId(attrId);
        if(role == null){return false;}
        if(role.getRoleKey().equals(BusinessConstants.COMPANY)){
            return true;
        }
        return false;
    }

    /**
     * 用户可以查看的小区列表
     * @param userId
     */
    @Override
    public List<CommunityManage> findCommunityByUserId(Long userId) {
        Long attrId = userMapper.selectUserById(userId).getAttrId();
        List<CommunityManage> communityManageList = new ArrayList<>();
        if(attrId == null || attrId == 0){
            return communityManageService.list(new CommunityManage());
        }else {
            String roleKey = this.checkUserRoleByAttrId(attrId).getRoleKey();
            Console.log("roleKey:"+roleKey);
            if (roleKey.equals(BusinessConstants.GOV) || roleKey.equals(BusinessConstants.COMPANY)){
                communityManageList = communityManageService.selectCommunityByAttrId(attrId);
            }else if (roleKey.equals(BusinessConstants.COMMUNITY)){
                CommunityManage communityManage = new CommunityManage().setCommunityId(attrId);
                communityManageList = communityManageService.list(communityManage);
            }
        }
        return communityManageList;
    }


    /**
     * 查询父级角色及子级，返回一个集合
     * @param attrId
     * @return
     */
    @Override
    public List<SysRole> selectRoleAndSonList(Long attrId,Long userId){
        List<SysRole> roleList = new ArrayList<>();
        SysRole roleFather = this.checkUserRoleByAttrId(attrId);
        roleList.add(roleFather);
        List<SysRole> roleSonList = roleMapper.selectRoleByParentId(roleFather.getRoleId());

        if(StringUtils.isNotNull(roleSonList) && roleSonList.size() > 0){
            roleList.addAll(roleSonList);
        }

        //对比已保存的
        if(StringUtils.isNotNull(userId)){
            List<SysRole> userRoles = roleMapper.selectRolesByUserId(userId);
            for (SysRole role : roleList) {
                for (SysRole userRole : userRoles) {
                    if (role.getRoleId().longValue() == userRole.getRoleId().longValue()) {
                        role.setFlag(true);
                        break;
                    }
                }
            }
        }
        return roleList;
    }

    /**
     * 查询公司的维保经理
     * @param userId
     * @return
     */
    @Override
    public List<SysUser> selectCompanyKeepManager(Long userId){
        SysUser user = userMapper.selectUserById(userId);
        List<SysUser> sysUserList = userMapper.selectUserList(new SysUser() {{
            setAttrId(user.getAttrId());
        }});

        List<SysUser> keepManagerList = new ArrayList<>();
        for (SysUser sysUser : sysUserList) {
            String roles = this.selectUserRole(sysUser.getUserId());
            if(roles.contains(BusinessConstants.KEEP_MANAGER)){
                keepManagerList.add(sysUser);
            }
        }
        return keepManagerList;
    }


    @Override
    public List<SysUser> selectCompanyManagerAndEngineer(Long userId) {
        SysUser user = userMapper.selectUserById(userId);
        List<SysUser> sysUserList = userMapper.selectUserList(new SysUser() {{
            setAttrId(user.getAttrId());
        }});

        List<SysUser> ManagerAndEngineerList = new ArrayList<>();
        for (SysUser sysUser : sysUserList) {
            String roles = this.selectUserRole(sysUser.getUserId());
            if(roles.contains(BusinessConstants.KEEP_MANAGER) ||roles.contains(BusinessConstants.KEEP_ENGINEER) ){
                ManagerAndEngineerList.add(sysUser);
            }
        }
        return ManagerAndEngineerList;
    }
}
